package sqlsession;

import com.mysql.jdbc.StringUtils;
import config.Configuration;
import config.MappedStatement;
import util.GenericTokenParser;
import util.ParameterMapping;
import util.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @CreatedBy richInfo AI
 * @ClassName SmpleExecutor
 * @Date 2021/8/16 2:43 下午
 * @Author xin.yang
 * @Description TODO
 */
public class SampleExecutor implements Executor
{

    @Override
    public <U> U selectList(MappedStatement mappedStatement, Configuration configuration, Object... args) throws Exception
    {
        Connection connection = configuration.getDatasource().getConnection();
        BoundsSql boundsSql = getBoundsSql(mappedStatement.getSql());
        PreparedStatement preparedStatement = connection.prepareStatement(boundsSql.getSql());
        List<ParameterMapping> parameterMappings = boundsSql.getParameterMappings();
        Class<?> parameterType = getClassType(mappedStatement.getParameterType());
        for (int i = 0; i < parameterMappings.size(); i++)
        {
            String content = parameterMappings.get(i).getContent();
            Field declaredField = parameterType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(args[0]);
            preparedStatement.setObject(i + 1, o);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        ArrayList<Object> list = new ArrayList<>();
        Class<?> resultType = getClassType(mappedStatement.getResultType());
        while (resultSet.next())
        {
            Object o = resultType.newInstance();
            for (int i = 1; i <= columnCount; i++)
            {
                String columnName = metaData.getColumnName(i);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                Object value = resultSet.getObject(columnName);
                writeMethod.invoke(o, value);
            }
            list.add(o);
        }
        return (U) list;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException
    {
        if (StringUtils.isNullOrEmpty(parameterType))
        {
            return null;
        }
        return Class.forName(parameterType);
    }

    private BoundsSql getBoundsSql(String sql)
    {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        return new BoundsSql(parse, parameterMappingTokenHandler.getParameterMappings());
    }

    @Override
    public int save(MappedStatement mappedStatement, Configuration configuration, Object... args) throws Exception
    {
        Connection connection = configuration.getDatasource().getConnection();
        Class<?> parameterType = getClassType(mappedStatement.getParameterType());
        BoundsSql boundsSql = getBoundsSql(mappedStatement.getSql());
        PreparedStatement preparedStatement = connection.prepareStatement(boundsSql.getSql());
        List<ParameterMapping> parameterMappings = boundsSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++)
        {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(args[0]);
            preparedStatement.setObject(i + 1, o);
        }
        int i = preparedStatement.executeUpdate();
        return i;
    }
}
